﻿using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using AirManager.Entities;


namespace AirManager
{
    public class Conexao : IDisposable
    {
        public static ISessionFactory CreateSessionFactory()
        {
            var dbConfig =
                MsSqlConfiguration.MsSql2005.ConnectionString("server=ESOUZANOTE-PC;database=master").UseReflectionOptimizer();
          
            var configuration = Fluently
                .Configure()
                .Database(dbConfig)
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf<Fleet>())
                .ExposeConfiguration(c => new SchemaExport(c).Create(false, false));

            return configuration.BuildSessionFactory();
        }

        private static ISession _currentSession;
        public static ISession CurrentSession
        {
            get { return _currentSession ?? (_currentSession = CreateSessionFactory().OpenSession()); }
        }

        public static void CloseSession()
        {
            if (_currentSession != null)
            {
                if (_currentSession.IsOpen)
                    _currentSession.Close();
                _currentSession = null;
            }
        }

        public void Dispose()
        {
            CloseSession();
        }
    }
}